package ding_talk_robot

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"time"
)

const reqUrl = "https://oapi.dingtalk.com/robot/send?access_token=e9e042464bd989a2837fef5e922bb2f384b8084b892eb2c67ef5178ae07cd507"

func SendMessage(message string) (map[string]interface{}, error) {
	secret := "SEC9328bfa503ff9e768ad3b1693aa8eeb533a6f868578d56e24f0f4d3269bf5e36" // 钉钉给出的密钥

	// 获取毫秒数时间戳
	milliSecTime := time.Now().UnixNano() / int64(time.Millisecond)

	// 拼装成待加密字符串
	stringToSign := fmt.Sprintf("%d\n%s", milliSecTime, secret)

	// 进行加密操作
	h := hmac.New(sha256.New, []byte(secret))
	h.Write([]byte(stringToSign))
	sign := base64.StdEncoding.EncodeToString(h.Sum(nil))
	sign = url.QueryEscape(sign)

	// 拼接url
	finalURL := fmt.Sprintf("%s&timestamp=%d&sign=%s", reqUrl, milliSecTime, sign)

	return send(finalURL, message)
}

// 发送消息
func send(url string, message string) (map[string]interface{}, error) {
	client := &http.Client{}
	data := map[string]interface{}{
		"msgtype": "text",
		"text": map[string]string{
			"content": message,
		},
	}

	jsonData, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("charset", "utf-8")

	res, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	var result map[string]interface{}
	if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
		return nil, err
	}

	return result, nil
}
